import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import moment from "moment";
import { Row, Col, Card, Icon, Button, Popconfirm, message, Divider, Form, Select, Input, Table} from "antd";
import RegionalSelection from "../../Form/RegionalSelection";
import styles from '../../Pbulic.less';

const FormItem = Form.Item;
const { Option } = Select;


const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');


@connect(({ path, global }) => ({
  dictionaries:global.dictionaries,
  selectSource:global.selectSource,
  resdata: path.resdata,
  loading: path.loading.reslist,
  pathcuring:path.pathcuring
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class AssodevChoose extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }



  componentDidMount() {
    const { pageSize } = this.state;

    // 获取区域数据
    this.props.dispatch({
      type: 'global/fetch_select_district',
    })
    // 列表
    this.getDataList({},pageSize,1);
  }

  componentWillReceiveProps(nextProps) {
    // 外层发起刷新数据请求
    if (nextProps.doAdd === true && this.props.doAdd === false) {
      this.setState({
        selectedRows:[]
      },()=>{
        this.props.refreshStop();
      })
    }
    if (nextProps.maintenanceId != this.props.maintenanceId) {
      this.getDataList({},pageSize,1);
    }
  }



  getDataList(params,pageSize,currentPage) {
    const { dispatch, maintenanceId } = this.props;
    maintenanceId && dispatch({
      type: 'path/fetch_curing_list',
      payload: {
        ...params,
        pageSize,
        currentPage,
        maintenanceId,
        region:undefined,
      },
    });
  }

  // 安装点位事件
  handleSearchDistrict = ( value ) =>{
    const { dispatch } = this.props;
    const districtId=value.districtId[value.districtId.length-1];
    const pointId=value.pointId;
    const loadPoint=value.loadPoint;

    if(pointId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_point',
      })
    }

    if(loadPoint && districtId!=0){
      dispatch({
        type: 'global/fetch_select_point',
        payload: {
          districtId,
        },
      })
    }

  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    form.resetFields();
    form.setFieldsValue({
      region:{districtId:[],pointId:0},
    })
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.devId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if(fieldsValue.region && fieldsValue.region.pointId!==0 && fieldsValue.region.districtId.length>0){
        fieldsValue.districtId = fieldsValue.region.districtId[fieldsValue.region.districtId.length - 1];
        fieldsValue.pointId = fieldsValue.region.pointId;
      }

      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };


  // 表格复选框选中
  handleSelectRows = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRows: selectedRows,
    },()=>{
      this.props.selectCallBack(selectedRows);
    });
  };



  // 搜索内容
  renderSearchForm() {
    const { form, dictionaries, selectSource } = this.props;
    const { getFieldDecorator } = form;
    const { selectedRows } = this.state;




    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} style={{paddingRight:0}}>
            <FormItem label="设备名称">
              {getFieldDecorator('devName')(<Input placeholder="请输入设备名称" />)}
            </FormItem>
          </Col>
          <Col md={14} sm={24} style={{paddingRight:0}}>
            <FormItem label="设备类型">
              {getFieldDecorator('devType')(
                <Select allowClear={true} placeholder="请选择设备类型" style={{ width: '100%' }}>
                  {dictionaries.deviceType && dictionaries.deviceType.map(item => (
                    <Option key={item.value} value={item.value}>{item.label}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>


        </Row>

        <Row gutter={{ md: 8, lg: 24, xl: 48 }} style={{marginTop:10}}>
          <Col md={16} sm={24} style={{paddingRight:0}}>
            <FormItem label="区域点位">
              {getFieldDecorator('region',{
              })(
                <RegionalSelection
                  districtData={selectSource.districtData}
                  pointData={selectSource.pointData}
                  onChange={this.handleSearchDistrict}
                />
              )}
            </FormItem>
          </Col>


          <Col md={8} sm={24} style={{paddingRight:0}}>
            <div >
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, pathcuring } = this.props;
    const { selectedRows } = this.state;



    const columns = [
      {
        title: '设备编号',
        dataIndex: 'devCode',
      },
      {
        title: '设备名称',
        dataIndex: 'devName',
      },
      {
        title: '区域',
        dataIndex: 'districtName',
      },
      {
        title: '点位',
        dataIndex: 'pointName',
      },
      {
        title: '上次养护时间',
        dataIndex: 'lastMaintainTime',
        render: text => text ? moment(text).format("YYYY-MM-DD HH:mm") : "--"
      },
    ];



    const rowSelection = {
      selectedRowKeys:selectedRows.map(item=>item.devId),
      onChange: this.handleSelectRows,
      getCheckboxProps: record => ({
        disabled:  pathcuring.map(item=>item.devId).some(item=>item==record.devId),
      }),
    };


    return (
      <Card bordered={false} bodyStyle={{padding:0}}>
        <div >
          <div className={styles.tableListSelectForm}>{this.renderSearchForm()}</div>
          <Table
            columns={columns}
            dataSource={resdata.list  ? resdata.list : []}
            pagination={resdata.pagination}
            rowSelection={rowSelection}
            onChange={this.handleStandardTableChange}
            loading={loading}
            rowKey={"devId"}
            size={"small"}
          />
        </div>
      </Card>

    );
  }
}
